// 自定义标签是可以有-和.的但是不在首位  '\\' 在字符串转义
const tagname = '[a-zA-Z_][\\-\\._0-9a-zA-Z]*'
// ?:表示结果匹配不保存
const tag = `((?:${tagname}\\:)?${tagname})`

const startTag = new RegExp(`^<${tag}`)
const startTagClose = /^\s*(\/?)>/
const endTag = new RegExp(`^<\\/${tag}[^>]*>`)
// ?:  处理的括号不会分组，不需要拿到正则匹配的结果
const attributes = /^\s*([^\s'"<>\/=]+)(?:\s*=\s*)(?:'([^']*)'|"([^"]*)")/

export const ELEMRNT_TYPE = 1
export const TEXT_TYPE = 3

export function parseHTML(template) {
  const strack = []
  let currentParent, root

  while (template) {
    template = template.trim()

    let textEnd = template.indexOf('<')
    // 如果<在开头那么就说明是标签
    if (!textEnd) {
      let startTagMatch = parseStartTag()
      if (startTagMatch) {
        handleStart(startTagMatch)
        continue
      }

      let endTagMatch = parseEndTag()
      if (endTagMatch) {
        handleEnd(endTagMatch)
        continue
      }
    } else {
      // <不在开头说明在标签的中间,是文本
      let text = template.slice(0, textEnd)
      handleText(text)
    }

  }

  function createASTElement(tag) {
    return {
      tag,
      type: ELEMRNT_TYPE,
      children: [],
      parent: null,
      attrs: [],
    }
  }

  function handleStart(match) {
    let node = createASTElement(match[1])
    advance(match[0].length)
    handleAttr(node)
    // 没有根节点,赋予
    if (!root) {
      root = node
    }
    if (currentParent) {
      node.parent = currentParent
      currentParent.children.push(node)
    }
    strack.push(node)
    currentParent = node
  }

  function handleAttr(node) {
    while (!parseStartTagClose()) {
      let attrMatch = parseAttr()
      if (attrMatch) {
        node.attrs.push({
          name: attrMatch[1],
          // 单引号或双引号
          value: attrMatch[2] || attrMatch[3]
        })
        advance(attrMatch[0].length)
      }
    }
    // 把开始标签的结束符删除
    advance(parseStartTagClose()[0].length)
  }

  function handleText(content) {
    // handleTemplateAttr(content)
    if (currentParent) {
      currentParent.children.push({
        content,
        type: TEXT_TYPE,
        parent: currentParent
      })
    }
    advance(content.length)
  }

  // 不在这里转化{{}}的变量
  // function handleTemplateAttr(content) {
  //   let templateAttrMatches = content.match(templateAttr)
  //   if (templateAttrMatches) {
  //     templateAttrMatches.forEach(match => {
  //       content = content.splice(match[0], match[0].length, vm[match[1]])
  //     });
  //   }
  // }

  function handleEnd(match) {
    strack.pop()
    currentParent = strack[strack.length - 1]
    advance(match[0].length)
  }

  function parseStartTag() {
    return template.match(startTag)
  }

  function parseStartTagClose() {
    return template.match(startTagClose)
  }

  function parseAttr() {
    return template.match(attributes)
  }

  function parseEndTag() {
    return template.match(endTag)
  }

  function advance(length) {
    template = template.slice(length)
  }


  return root
}
